package com.ihr360.payroll.controller.attendanceReport;

import com.google.common.collect.Lists;
import com.ihr360.alps.ServiceDescriptor;
import com.ihr360.commons.entity.AuthUserInfo;
import com.ihr360.commons.exception.Ihr360Exception;
import com.ihr360.commons.lang.CollectionUtils;
import com.ihr360.commons.lang.StringUtils;
import com.ihr360.commons.model.type.ProgressType;
import com.ihr360.commons.request.Ihr360SearchBody;
import com.ihr360.commons.vo.PageData;
import com.ihr360.commons.vo.ResultInfo;
import com.ihr360.entity.BasicStaffInfoEntity;
import com.ihr360.excel.vo.ImportRequest;
import com.ihr360.maven.plugin.ModuleCodeStore;
import com.ihr360.maven.plugin.annotation.FunctionDefinition;
import com.ihr360.maven.plugin.annotation.ModuleDefinition;
import com.ihr360.payroll.dao.AttendanceMonthlyReportSummaryRepository;
import com.ihr360.payroll.model.dto.attendance.report.AttendanceMonthlyReportSummary;
import com.ihr360.payroll.model.vo.AttendanceSummaryVo;
import com.ihr360.payroll.request.attendance.AttendanceOverTimeRequest;
import com.ihr360.payroll.request.attendance.AttendanceTakeNumberRequest;
import com.ihr360.payroll.response.attendance.AttendanceSummaryResponse;
import com.ihr360.payroll.service.attendancereport.AttendanceMonthlyReportSummaryService;
import com.ihr360.payroll.type.AttendanceState;
import com.ihr360.rest.service.SimpleRestService;
import com.ihr360.rest.webmvc.AbstractRestSimpleWithLongIdController;
import com.ihr360.shared.advice.response.DisableResponseAdvice;
import com.ihr360.shared.basicstaffinfo.service.BasicStaffInfoService;
import com.ihr360.sharedservice.api.DataCacheService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Eric on 2018/3/23/023.
 */
@Api("考勤汇总接口")
@Controller
@RequestMapping(value = "/attendanceSummaryReport")
@ModuleDefinition(mainModuleCode = ModuleCodeStore.Module.SALARY_CODE,
        mainModuleName = ModuleCodeStore.Module.SALARY_NAME,
        subModuleCode = ModuleCodeStore.Module.Salary.SALARY_ATTENDANCE_CODE,
        subModuleName = ModuleCodeStore.Module.Salary.SALARY_ATTENDANCE_NAME,
        hasExtendsAbstractRestController = true)
public class AttendanceMonthlyReportSummaryController extends AbstractRestSimpleWithLongIdController<AttendanceMonthlyReportSummary> {

    @Autowired
    private AttendanceMonthlyReportSummaryService attendanceMonthlyReportSummaryService;
    @Autowired
    private BasicStaffInfoService basicStaffInfoService;
    @Autowired
    private DataCacheService dataCacheService;
    @Autowired
    private AttendanceMonthlyReportSummaryRepository reportSummaryRepository;

    @Override
    public SimpleRestService<AttendanceMonthlyReportSummary, Long> getSimpleRestService() {
        return attendanceMonthlyReportSummaryService;
    }

    @FunctionDefinition(functionName = "获取考勤汇总列表", functionCode = ModuleCodeStore.Function.VIEW)
    @ApiOperation(value = "获取考勤汇总列表")
    @PostMapping(value = "/list", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public PageData<AttendanceSummaryVo> summaryList(AuthUserInfo userInfo, @RequestBody Ihr360SearchBody<AttendanceMonthlyReportSummary> searchBody) {
        //查询列表
        PageData<AttendanceMonthlyReportSummary> pageData = attendanceMonthlyReportSummaryService.getSummaryList(userInfo, searchBody.getPageable());
        //获取列表同步状态
        List<AttendanceSummaryVo> list = Lists.newArrayList();
        if (pageData == null || CollectionUtils.isEmpty(pageData.getContent())) {
            return new PageData<>(0, 0, list);
        }
        for (AttendanceMonthlyReportSummary attendanceMonthlyReportSummary : pageData.getContent()) {
            AttendanceSummaryVo attendanceSummaryVo = new AttendanceSummaryVo();
            BeanUtils.copyProperties(attendanceMonthlyReportSummary, attendanceSummaryVo);
            //查询进度
            String progress = dataCacheService.get(ProgressType.ATTENDANCE_SUMMARY.name() + attendanceMonthlyReportSummary.getId());
            if (StringUtils.isNotEmpty(progress)) {
                attendanceSummaryVo.setIsDone(false);
                attendanceSummaryVo.setTime(Integer.valueOf(progress));
            } else {
                attendanceSummaryVo.setIsDone(true);
            }
            attendanceSummaryVo.setId(attendanceMonthlyReportSummary.getId());
            list.add(attendanceSummaryVo);
        }
        return new PageData<>(pageData.getTotalPages(), pageData.getTotalElements(), list);
    }

    @FunctionDefinition(functionName = "考勤汇总导入", functionCode = ModuleCodeStore.Function.IMPORT)
    @ApiOperation(value = "考勤汇总导入")
    @PostMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultInfo upload(AuthUserInfo userInfo, @RequestBody ImportRequest importRequest) {
        ResultInfo resultInfo = new ResultInfo();
        attendanceMonthlyReportSummaryService.importSummary(userInfo, importRequest);
        resultInfo.setCode(0);
        resultInfo.setMessage("考勤汇总导入成功");
        return resultInfo;
    }

    @FunctionDefinition(functionName = "考勤汇总取数方式", functionCode = ModuleCodeStore.Function.ATTENDANCE_TAKE_NUMBER)
    @ApiOperation(value = "/takeNumber/summary", notes = "考勤汇总取数方式")
    @PostMapping(value = "/takeNumber/summary", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @DisableResponseAdvice
    public AttendanceSummaryResponse takeNumberSummary(@RequestBody AttendanceTakeNumberRequest request) {
        AttendanceSummaryResponse response = new AttendanceSummaryResponse();
        response.setSummaryId(attendanceMonthlyReportSummaryService.takeNumberSummary(request.getUserInfo(), request));
        return response;
    }

    @FunctionDefinition(functionName = "考勤汇总取数同步月报日报数据", functionCode = ModuleCodeStore.Function.ATTENDANCE_TAKE_NUMBER)
    @ApiOperation(value = "/takeNumber/monthlyReport", notes = "考勤汇总取数，同步月报日报数据")
    @PostMapping(value = "/takeNumber/monthlyReport")
    public void takeNumberMonthlyReport(@RequestBody AttendanceTakeNumberRequest request) {
        attendanceMonthlyReportSummaryService.takeNumberMonthlyReport(request.getUserInfo(), request);
    }

    @FunctionDefinition(functionName = "考勤汇总模板下载", functionCode = ModuleCodeStore.Function.IMPORT)
    @ApiOperation(value = "考勤汇总模板下载")
    @GetMapping(value = "/template", produces = ("text/html;charset=UTF-8"))
    public void template(HttpServletResponse response) throws IOException {
        response.setHeader("x-filename", URLEncoder.encode("考勤汇总导入模板.xls", "UTF-8"));
        attendanceMonthlyReportSummaryService.excelTemplateDownload(response.getOutputStream());
    }

    @FunctionDefinition(functionName = "查询员工信息", functionCode = ModuleCodeStore.Function.ATTENDANCE_TAKE_NUMBER)
    @ApiOperation(value = "查询员工信息")
    @PostMapping(value = "/queryStaff")
    public List<BasicStaffInfoEntity> queryOneStaff(AuthUserInfo userInfo, @RequestBody List<String> staffIds) {
        return basicStaffInfoService.getStaffList(userInfo.getCompanyId(), staffIds);
    }

    @FunctionDefinition(functionName = "查询自定义列表", functionCode = ModuleCodeStore.Function.VIEW)
    @ApiOperation(value = "查询自定义列表")
    @GetMapping(value = "/queryCustomField")
    public ServiceDescriptor queryCustomField(AuthUserInfo userInfo) {
        return attendanceMonthlyReportSummaryService.serviceDescriptor(userInfo.getCompanyId());
    }

    @FunctionDefinition(functionName = "考勤汇总锁定/撤销锁定", functionCode = ModuleCodeStore.Function.ATTENDANCE_LOCK)
    @ApiOperation(value = "考勤汇总锁定/撤销锁定")
    @GetMapping(value = "/lockAttendanceState")
    @DisableResponseAdvice
    public AttendanceOverTimeRequest lockAttendanceState(@RequestParam Long summaryId, @RequestParam AttendanceState state) {
        if (summaryId == null || state == null) {
            throw new Ihr360Exception(null, "汇总信息状态不可为空");
        }
        return attendanceMonthlyReportSummaryService.lockAttendanceState(summaryId, state);
    }

    @FunctionDefinition(functionName = "考勤汇总校验是否存在", functionCode = ModuleCodeStore.Function.VIEW, isPublic = true)
    @ApiOperation(value = "考勤汇总校验是否存在")
    @PostMapping(value = "/checkSummaryExist")
    @DisableResponseAdvice
    public Boolean checkSummaryExist(AuthUserInfo userInfo, @RequestBody AttendanceTakeNumberRequest request) {
        Calendar c = Calendar.getInstance();
        c.setTime(request.getSummaryDate());
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        return attendanceMonthlyReportSummaryService.checkSummaryExist(userInfo.getCompanyId(), year, month, request.getSalaryPlanId());
    }

    @ApiOperation(value = "考勤汇总回滚删除")
    @GetMapping(value = "/deleteSummary")
    @Transactional
    @FunctionDefinition(functionName = "考勤汇总回滚删除", functionCode = ModuleCodeStore.Function.DELETE, isPublic = true)
    public void deleteSummary(@RequestParam Long summaryId) {
        reportSummaryRepository.delete(summaryId);
        dataCacheService.remove(ProgressType.ATTENDANCE_SUMMARY.name() + summaryId);
    }

    @ApiOperation(value = "考勤汇总回滚锁定状态")
    @GetMapping(value = "/rollBackState")
    @Transactional
    @FunctionDefinition(functionName = "考勤汇总回滚锁定状态", functionCode = ModuleCodeStore.Function.UPDATE, isPublic = true)
    public void rollBackState(@RequestParam Long summaryId, @RequestParam AttendanceState state) {
        AttendanceMonthlyReportSummary summary = reportSummaryRepository.findOne(summaryId);
        summary.setState(state);
        reportSummaryRepository.save(summary);
    }


}
